package projet.volleystat;

import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;

import projet.volleystat.automate.MarkedPointVolleyAction;
import projet.volleystat.automate.MatchVolleyFaultAction;
import projet.volleystat.automate.PassVolleyAction;
import projet.volleystat.automate.ReplacementVolleyAction;
import projet.volleystat.automate.ServiceVolleyAction;
import projet.volleystat.automate.VolleyStateMachineException;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.View;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MatchActivity extends Activity {
	protected Court court;
	protected Team myteam;
	protected Team advteam;
	protected Team myteamtemp;
	protected Team advteamtemp;
	protected TextView advteamtext;
	protected TextView myteamtext;
	protected TextView advscore;
	protected TextView myscore;
	protected TextView mywinsets;
	protected TextView advwinsets;
	protected SparseArray<Player> myplayers;
	protected SparseArray<Player> advplayers;
	protected ArrayList<Player> myreplacementplayers;
	protected ArrayList<Player> advreplacementplayers;
	protected TreeMap<Integer, Player> myreplacementplayersmap;
	protected TreeMap<Integer, Player> advreplacementplayersmap;
	protected SparseArray<Button> myplayersb;
	protected SparseArray<Button> advplayersb;
	protected ArrayList<Player> allmyplayers;
	protected ArrayList<Player> alladvplayers;
	protected Button serveb;
	protected Button faultb;
	protected DBInfo dbinfo;
	protected Button brightbutton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_match);
		int[] myplayersbid = new int[] { R.id.myteamplayerb1,
				R.id.myteamplayerb2, R.id.myteamplayerb3, R.id.myteamplayerb4,
				R.id.myteamplayerb5, R.id.myteamplayerb6 };

		int[] advplayersbid = new int[] { R.id.advteamplayerb1,
				R.id.advteamplayerb2, R.id.advteamplayerb3,
				R.id.advteamplayerb4, R.id.advteamplayerb5,
				R.id.advteamplayerb6 };
		
		myteamtext = (TextView) findViewById(R.id.myteamtext);
		advteamtext = (TextView) findViewById(R.id.advteamtext);

		myscore = (TextView) findViewById(R.id.myscore);
		advscore = (TextView) findViewById(R.id.advscore);
		mywinsets = (TextView) findViewById(R.id.mywinsets);
		advwinsets = (TextView) findViewById(R.id.advwinsets);

		myplayersb = new SparseArray<Button>();
		advplayersb = new SparseArray<Button>();

		myplayers = new SparseArray<Player>();
		advplayers = new SparseArray<Player>();

		allmyplayers = new ArrayList<Player>();
		alladvplayers = new ArrayList<Player>();

		for (int i = 1; i <= 6; i++) {
			((Button) findViewById(advplayersbid[i - 1])).setBackgroundColor(R.color.gris);
			((Button) findViewById(myplayersbid[i - 1])).setBackgroundColor(R.color.gris);
			
			myplayersb.append(i, (Button) findViewById(myplayersbid[i - 1]));
			advplayersb.append(i, (Button) findViewById(advplayersbid[i - 1]));
		}
		serveb = (Button) findViewById(R.id.serveb);
		faultb = (Button) findViewById(R.id.faultb);

		dbinfo = new DBInfo(getApplicationContext());
		dbinfo.openDb();

		Bundle bundle = getIntent().getExtras();
		int[] myplayersarray = bundle.getIntArray("myplayersarray");
		int[] advplayersarray = bundle.getIntArray("advplayersarray");
		ArrayList<Integer> myreplacementplayersid = bundle
				.getIntegerArrayList("myreplacementplayersarray");
		ArrayList<Integer> advreplacementplayersid = bundle
				.getIntegerArrayList("advreplacementplayersarray");

		myreplacementplayers = new ArrayList<Player>();
		advreplacementplayers = new ArrayList<Player>();

		myreplacementplayersmap = new TreeMap<Integer, Player>();
		advreplacementplayersmap = new TreeMap<Integer, Player>();

		try {
			myteam = dbinfo.getDb().getTeamById(bundle.getInt("myteamid"));
			advteam = dbinfo.getDb().getTeamById(bundle.getInt("advteamid"));
		} catch (DatabaseException e) {
			e.printStackTrace();
		}

		for (int i = 1; i <= 6; i++) {
			try {
				Player player = dbinfo.getDb().getPlayerById(myplayersarray[i]);
				myplayers.put(i, player);
				allmyplayers.add(player);
			} catch (DatabaseException e) {
				e.printStackTrace();
			}
		}
		for (int i = 1; i <= 6; i++) {
			try {
				Player player = dbinfo.getDb()
						.getPlayerById(advplayersarray[i]);
				advplayers.put(i, player);
				alladvplayers.add(player);
			} catch (DatabaseException e) {
				e.printStackTrace();
			}
		}

		for (int i = 0; i < myreplacementplayersid.size(); i++) {
			try {
				allmyplayers.add(dbinfo.getDb().getPlayerById(
						myreplacementplayersid.get(i)));
				myreplacementplayers.add(dbinfo.getDb().getPlayerById(
						myreplacementplayersid.get(i)));
				myreplacementplayersmap.put(
						myreplacementplayersid.get(i),
						dbinfo.getDb().getPlayerById(
								myreplacementplayersid.get(i)));
			} catch (DatabaseException e) {
				e.printStackTrace();
			}
		}

		for (int i = 0; i < advreplacementplayersid.size(); i++) {
			try {
				alladvplayers.add(dbinfo.getDb().getPlayerById(
						advreplacementplayersid.get(i)));
				advreplacementplayers.add(dbinfo.getDb().getPlayerById(
						advreplacementplayersid.get(i)));
				advreplacementplayersmap.put(
						advreplacementplayersid.get(i),
						dbinfo.getDb().getPlayerById(
								advreplacementplayersid.get(i)));
			} catch (DatabaseException e) {
				e.printStackTrace();
			}
		}

		try {
			myteamtemp = dbinfo.getDb().getTeamById(bundle.getInt("myteamid"));
			advteamtemp = dbinfo.getDb()
					.getTeamById(bundle.getInt("advteamid"));
			myteam = new Team(myteamtemp.getId(), myteamtemp.getName(),
					myteamtemp.getCountry(), allmyplayers);
			advteam = new Team(advteamtemp.getId(), advteamtemp.getName(),
					advteamtemp.getCountry(), alladvplayers);
		} catch (DatabaseException e) {
			e.printStackTrace();
		}

		for (int i = 1; i <= 6; i++) {
			myplayersb.get(i).setText(myplayers.get(i).getName());
			advplayersb.get(i).setText(advplayers.get(i).getName());
		}

		myteamtext.setText(myteam.getName());
		advteamtext.setText(advteam.getName());

		myscore.setText("0");
		advscore.setText("0");
		mywinsets.setText("0");
		advwinsets.setText("0");

		dbinfo.closeDb();

		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		builder.setMessage(R.string.dialog_select_team);

		builder.setPositiveButton(R.string.me,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						court = new Court(myteam, advteam, myteam, dbinfo,
								MatchActivity.this);
					}
				});

		builder.setNegativeButton(R.string.adv,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						court = new Court(myteam, advteam, advteam, dbinfo,
								MatchActivity.this);
					}
				});

		AlertDialog dialog = builder.create();
		dialog.show();

		serveb.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				try {
					court.signalAction(new ServiceVolleyAction());
				} catch (VolleyStateMachineException e) {
					Toast toast = Toast.makeText(MatchActivity.this,
							R.string.invalidaction, Toast.LENGTH_SHORT);
					toast.show();
				}
			}
		});

		for (int i = 1; i <= 6; i++) {
			final int idmyteamb = i;
			myplayersb.get(i).setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					try {
						System.out.println("Passe 1");
						court.signalAction(new PassVolleyAction(myteam,
								myplayers.get(idmyteamb), (short) 1));
						if (brightbutton != null) {
							brightbutton.setBackgroundResource(0);
							brightbutton.setBackgroundColor(R.color.gris);
						}
						brightbutton = myplayersb.get(idmyteamb);
						myplayersb.get(idmyteamb).setBackgroundResource(R.drawable.ball);
					} catch (VolleyStateMachineException e) {
						Toast toast = Toast.makeText(MatchActivity.this,
								R.string.invalidaction, Toast.LENGTH_SHORT);
						toast.show();
					}
				}
			});

			myplayersb.get(i).setOnLongClickListener(
					new View.OnLongClickListener() {

						@Override
						public boolean onLongClick(View v) {
							AlertDialog.Builder builderb = new AlertDialog.Builder(
									MatchActivity.this);
							builderb.setMessage("Action");
							builderb.setPositiveButton("Balle in",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											try {
												court.signalAction(new MarkedPointVolleyAction(
														(short) 2, myplayers
																.get(idmyteamb)));
											} catch (VolleyStateMachineException e) {
												Toast toast = Toast.makeText(
														MatchActivity.this,
														R.string.invalidaction,
														Toast.LENGTH_SHORT);
												dialog.cancel();
												toast.show();
											}
										}
									});

							builderb.setNegativeButton("Remplacer",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											Intent intent = new Intent(
													getApplicationContext(),
													SelectPlayerActivity.class);
											ArrayList<Integer> playersarray = new ArrayList<Integer>();

											System.out
													.println(myreplacementplayers
															.size());

											for (Map.Entry<Integer, Player> entry : myreplacementplayersmap
													.entrySet()) {
												playersarray.add(entry.getKey());
											}

											intent.putExtra("playersarray",
													playersarray);
											intent.addFlags(android.content.Intent.FLAG_ACTIVITY_NO_ANIMATION);
											startActivityForResult(intent,
													10 + idmyteamb);
										}
									});

							AlertDialog dialogb = builderb.create();
							dialogb.show();
							return false;
						}
					});
		}

		for (int i = 1; i <= 6; i++) {
			final int idadvteamb = i;
			advplayersb.get(i).setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					try {
						System.out.println("Passe 2");
						court.signalAction(new PassVolleyAction(advteam,
								advplayers.get(idadvteamb), (short) 1));
						if (brightbutton != null) {
							brightbutton.setBackgroundResource(0);
							brightbutton.setBackgroundColor(R.color.gris);
						}
						brightbutton = advplayersb.get(idadvteamb);
						brightbutton.setBackgroundResource(R.drawable.ball);
					} catch (VolleyStateMachineException e) {
						Toast toast = Toast.makeText(MatchActivity.this,
								R.string.invalidaction, Toast.LENGTH_SHORT);
						toast.show();
					}
				}
			});

			advplayersb.get(i).setOnLongClickListener(
					new View.OnLongClickListener() {

						@Override
						public boolean onLongClick(View v) {
							AlertDialog.Builder builderb = new AlertDialog.Builder(
									MatchActivity.this);
							builderb.setMessage("Action");
							builderb.setPositiveButton("Balle in",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											try {
												court.signalAction(new MarkedPointVolleyAction(
														(short) 2,
														advplayers
																.get(idadvteamb)));
											} catch (VolleyStateMachineException e) {
												Toast toast = Toast.makeText(
														MatchActivity.this,
														R.string.invalidaction,
														Toast.LENGTH_SHORT);
												dialog.cancel();
												toast.show();
											}
										}
									});

							builderb.setNegativeButton("Remplacer",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											Intent intent = new Intent(
													getApplicationContext(),
													SelectPlayerActivity.class);
											ArrayList<Integer> playersarray = new ArrayList<Integer>();

											for (Map.Entry<Integer, Player> entry : advreplacementplayersmap
													.entrySet()) {
												playersarray.add(entry.getKey());
											}

											intent.putExtra("playersarray",
													playersarray);
											intent.addFlags(android.content.Intent.FLAG_ACTIVITY_NO_ANIMATION);
											startActivityForResult(intent,
													20 + idadvteamb);
										}
									});

							AlertDialog dialogb = builderb.create();
							dialogb.show();
							return false;
						}
					});
		}

		faultb.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				final CharSequence[] faults = { "Faute de position",
						"Balle out", "Faute au fil", "Faute de penetration",
						"Faute de contre", "Faute des quatre touches",
						"Faute des deux touches", "Faute de frappe d'attaque",
						"Ballon tenu" };

				AlertDialog.Builder builder = new AlertDialog.Builder(
						MatchActivity.this);
				builder.setTitle("Faute");
				builder.setItems(faults, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case 0:
							try {
								court.signalAction(new MatchVolleyFaultAction(1));
							} catch (VolleyStateMachineException e) {
								Toast toast = Toast.makeText(
										MatchActivity.this,
										R.string.invalidaction,
										Toast.LENGTH_SHORT);
								toast.show();
							}
							break;
						case 1:
							try {
								court.signalAction(new MatchVolleyFaultAction(4));
							} catch (VolleyStateMachineException e) {
								Toast toast = Toast.makeText(
										MatchActivity.this,
										R.string.invalidaction,
										Toast.LENGTH_SHORT);
								toast.show();
							}
							break;
						case 2:
							try {
								court.signalAction(new MatchVolleyFaultAction(5));
							} catch (VolleyStateMachineException e) {
								Toast toast = Toast.makeText(
										MatchActivity.this,
										R.string.invalidaction,
										Toast.LENGTH_SHORT);
								toast.show();
							}
							break;
						case 3:
							try {
								court.signalAction(new MatchVolleyFaultAction(6));
							} catch (VolleyStateMachineException e) {
								Toast toast = Toast.makeText(
										MatchActivity.this,
										R.string.invalidaction,
										Toast.LENGTH_SHORT);
								toast.show();
							}
							break;
						case 4:
							try {
								court.signalAction(new MatchVolleyFaultAction(
										11));
							} catch (VolleyStateMachineException e) {
								Toast toast = Toast.makeText(
										MatchActivity.this,
										R.string.invalidaction,
										Toast.LENGTH_SHORT);
								toast.show();
							}
							break;
						case 5:
							try {
								court.signalAction(new MatchVolleyFaultAction(3));
							} catch (VolleyStateMachineException e) {
								Toast toast = Toast.makeText(
										MatchActivity.this,
										R.string.invalidaction,
										Toast.LENGTH_SHORT);
								toast.show();
							}
							break;
						case 6:
							try {
								court.signalAction(new MatchVolleyFaultAction(7));
							} catch (VolleyStateMachineException e) {
								Toast toast = Toast.makeText(
										MatchActivity.this,
										R.string.invalidaction,
										Toast.LENGTH_SHORT);
								toast.show();
							}
							break;
						case 7:
							try {
								court.signalAction(new MatchVolleyFaultAction(8));
							} catch (VolleyStateMachineException e) {
								Toast toast = Toast.makeText(
										MatchActivity.this,
										R.string.invalidaction,
										Toast.LENGTH_SHORT);
								toast.show();
							}
							break;
						case 9:
							try {
								court.signalAction(new MatchVolleyFaultAction(9));
							} catch (VolleyStateMachineException e) {
								Toast toast = Toast.makeText(
										MatchActivity.this,
										R.string.invalidaction,
										Toast.LENGTH_SHORT);
								toast.show();
							}
							break;
						}
					}
				});

				AlertDialog dialog = builder.create();
				dialog.show();
			}
		});

	}

	public void resetBrightButton() {
		if (brightbutton != null) {
			brightbutton.setBackgroundResource(0);
			brightbutton.setBackgroundColor(R.color.gris);
			brightbutton = null;
		}
	}

	public void setBrightButtonFirstPosPlayerTeam(Team team) {
		if (brightbutton != null) {
			brightbutton.setBackgroundResource(R.drawable.ball);
		}
		if (team.getId() == myteam.getId()) {
			brightbutton = myplayersb.get(1);
		} else {
			brightbutton = advplayersb.get(1);
		}
		brightbutton.setBackgroundResource(R.drawable.ball);
	}

	public void setMyScore(String score) {
		myscore.setText(score);
	}

	public void setAdvScore(String score) {
		advscore.setText(score);
	}

	public void setMyWinSets(String score) {
		mywinsets.setText(score);
	}

	public void setAdvWinSets(String score) {
		advwinsets.setText(score);
	}

	public void setMyPlayers(SparseArray<Player> players) {
		myplayers = players;
		for (int i = 1; i <= 6; i++) {
			myplayersb.get(i).setText(myplayers.get(i).getName());
		}
	}

	public void setAdvPlayers(SparseArray<Player> players) {
		advplayers = players;
		for (int i = 1; i <= 6; i++) {
			advplayersb.get(i).setText(advplayers.get(i).getName());
		}
	}

	public void setMyReplacementPlayers(TreeMap<Integer, Player> players) {
		ArrayList<Player> replacement = new ArrayList<Player>();
		for (Map.Entry<Integer, Player> entry : players.entrySet()) {
			replacement.add(entry.getValue());
		}
		myreplacementplayers = replacement;
	}

	public void setAdvReplacementPlayers(TreeMap<Integer, Player> players) {
		ArrayList<Player> replacement = new ArrayList<Player>();
		for (Map.Entry<Integer, Player> entry : players.entrySet()) {
			replacement.add(entry.getValue());
		}
		advreplacementplayers = replacement;
	}

	public void matchEnding() {
		int id = 0;

		try {
			id = court.registerStat();
		} catch (DatabaseException e) {
			e.printStackTrace();
		}

		ArrayList<Integer> playersid = new ArrayList<Integer>();

		for (int i = 0; i < allmyplayers.size(); i++) {
			playersid.add(allmyplayers.get(i).getId());
		}

		for (int i = 0; i < alladvplayers.size(); i++) {
			playersid.add(alladvplayers.get(i).getId());
		}

		Intent intent = new Intent(getApplicationContext(),
				EndMatchActivity.class);

		intent.putExtra("playersid", playersid);
		intent.putExtra("idmatch", id);

		intent.addFlags(android.content.Intent.FLAG_ACTIVITY_NO_ANIMATION);

		startActivity(intent);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		for (int i = 11; i <= 16; i++) {
			if (requestCode == i) {
				if (resultCode == Activity.RESULT_OK) {
					try {
						Player player = myreplacementplayersmap.get(data
								.getIntExtra("selectedplayerid", -1));
						court.signalAction(new ReplacementVolleyAction(myteam,
								myplayers.get(i - 10), player));
						myreplacementplayersmap.remove(data.getIntExtra(
								"selectedplayerid", -1));
						myreplacementplayersmap.put(myplayers.get(i - 10)
								.getId(), myplayers.get(i - 10));
						setMyReplacementPlayers(myreplacementplayersmap);
					} catch (VolleyStateMachineException e) {
						Toast toast = Toast.makeText(MatchActivity.this,
								R.string.invalidaction, Toast.LENGTH_SHORT);
						toast.show();
					}
					break;
				}
			}
		}

		for (int i = 21; i <= 26; i++) {
			if (requestCode == i) {
				if (resultCode == Activity.RESULT_OK) {
					try {
						Player player = advreplacementplayersmap.get(data
								.getIntExtra("selectedplayerid", -1));
						court.signalAction(new ReplacementVolleyAction(advteam,
								advplayers.get(i - 20), player));
						advreplacementplayersmap.remove(data.getIntExtra(
								"selectedplayerid", -1));
						advreplacementplayersmap.put(myplayers.get(i - 20)
								.getId(), advplayers.get(i - 20));
						setAdvReplacementPlayers(advreplacementplayersmap);
					} catch (VolleyStateMachineException e) {
						Toast toast = Toast.makeText(MatchActivity.this,
								R.string.invalidaction, Toast.LENGTH_SHORT);
						toast.show();
					}
					break;
				}
			}
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		dbinfo.openDb();
	}

	@Override
	public void onPause() {
		super.onPause();
		dbinfo.closeDb();
		overridePendingTransition(0, 0);
	}
}
